import { useQuery } from "@tanstack/react-query";

import { useAuth } from "@/contexts/auth-context";
import { useApiFetch } from "@/lib/api-fetcher";
import type { ProjectDetail } from "@/lib/types";

export function useProjectQuery(projectId: string, initialData?: ProjectDetail | null) {
  const fetcher = useApiFetch();
  const { tokens } = useAuth();

  return useQuery<ProjectDetail | null, Error>({
    queryKey: ["projects", projectId],
    queryFn: async () => {
      if (!tokens) {
        return null;
      }

      return fetcher<ProjectDetail>({ path: `/projects/${projectId}` });
    },
    initialData: initialData ?? null,
    enabled: Boolean(tokens && projectId),
    staleTime: 30 * 1000,
  });
}
